package com.example.demospring.service.counselor;

import com.example.demospring.entity.AdditionalTimeAppointment;
import com.example.demospring.dto.counselor.AdditionalTimeAppointmentDTO;
import com.example.demospring.repository.AdditionalTimeAppointmentRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class AdditionalTimeAppointmentService {

    @Autowired
    private AdditionalTimeAppointmentRepository repository;

    public Page<AdditionalTimeAppointmentDTO> findPage(String name, java.time.LocalDate date, String timeSlot, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by("date").descending());

        AdditionalTimeAppointment probe = new AdditionalTimeAppointment();
        if (name != null && !name.isEmpty()) probe.setName(name);
        if (date != null) probe.setDate(date);
        if (timeSlot != null && !timeSlot.isEmpty()) probe.setTimeSlot(timeSlot);

        ExampleMatcher matcher = ExampleMatcher.matchingAll()
                .withIgnoreNullValues()
                .withMatcher("name", match -> match.contains());

        Page<AdditionalTimeAppointment> pageResult = repository.findAll(Example.of(probe, matcher), pageable);

        return pageResult.map(this::toDTO);
    }

    public AdditionalTimeAppointmentDTO getById(Integer id) {
        return repository.findById(id).map(this::toDTO).orElse(null);
    }

    public AdditionalTimeAppointmentDTO saveOrUpdate(AdditionalTimeAppointmentDTO dto) {
        AdditionalTimeAppointment entity;
        if (dto.getId() != null) {
            entity = repository.findById(dto.getId()).orElse(new AdditionalTimeAppointment());
        } else {
            entity = new AdditionalTimeAppointment();
            entity.setCreatedAt(LocalDateTime.now());
        }
        BeanUtils.copyProperties(dto, entity, "id", "createdAt");
        entity.setUpdatedAt(LocalDateTime.now());
        AdditionalTimeAppointment saved = repository.save(entity);
        return toDTO(saved);
    }

    public void delete(Integer id) {
        repository.deleteById(id);
    }

    private AdditionalTimeAppointmentDTO toDTO(AdditionalTimeAppointment entity) {
        AdditionalTimeAppointmentDTO dto = new AdditionalTimeAppointmentDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
}